/*******************************************************************************
 * 
 ******************************************************************************/
var addUserWin;
var updateUserWin;
var userAddForm;
var userUpdateForm;
var userGrid;
var u_l_store;
var u_s_store;
var u_cm;
var u_sel_ids = [];
var u_sel_name;

var addRoleWin;
var updateRoleWin;
var searchRoleWin;
var roleAddForm;
var roleUpdateForm;
var roleGrid;
var ro_l_store;
var ro_s_store;
var ro_cm;
var ro_sel_ids = [];
var ro_sel_name;
var current_selected_id;
var current_selected_name;
var addResourcesGrid;
var addResourcesWin;

var addResourceWin;
var updateResourceWin;
var resourceAddForm;
var resourceUpdateForm;
var resourceGrid;
var re_l_store;
var re_s_store;
var re_cm;
var re_sel_ids = [];
var re_sel_name;

var pageSize = 5;

Ext.onReady(function() {
	var current_selected_name;

	Ext.QuickTips.init();

	Ext.form.Field.prototype.msgTarget = "side";

	Ext.BLANK_IMAGE_URL = "http://localhost/extjstest/resources/images/default/s.gif";

	Ext.apply(Ext.form.VTypes, {
				"tel" : function(_v) {

					if (/^\d+$/.test(_v)) {
						return true;
					}

					return false;

				},
				"telText" : "该输入项必须是电话格式,格式如:150...",
				"ageMask" : /[0-9]/i
			});
	Ext.apply(Ext.form.VTypes, {
		"role" : function(_v) {
			// alert( _v.substring(0,5))
			if ("ROLE_" == _v.substring(0, 5)) {
				return true;
			}

			return false;

		},
		"roleText" : "该输入项必须是电话格式,格式必须以'ROLE_'开头"
			// "roleMask" : /[0-9]/i
		});
	Ext.apply(Ext.form.VTypes, {
				password : function(val, field) {// val指这里的文本框值，field指这个文本框组件，大家要明白这个意思
					if (field.confirmTo) {// confirmTo是我们自定义的配置参数，一般用来保存另外的组件的id值
						var pwd = Ext.get(field.confirmTo);// 取得confirmTo的那个id的值
						return (val == pwd.getValue());
					}
					return true;
				},
				"passwordText" : "两次密码不一致!"

			});

	// var _panel = new PersonListGridPanel();
	/** *************************************************** */

	TopicRecord = Ext.data.Record.create([{
				name : 'id',
				mapping : 'role.id'
			}, {
				name : 'name',
				mapping : 'role.name'
			}, {
				name : 'discription',
				mapping : 'role.discription'
			}]);

	roleAddForm = new Ext.form.FormPanel({
				url : "roleAction!add.action",
				// url : "roleAction!update.action",
				method : 'post',
				defaultType : "textfield",
				labelWidth : 55,
				defaults : {
					anchor : "92%"
				},
				baseCls : "x-plain",
				items : [{
							fieldLabel : "名称",
							vtype : "role",
							value : "ROLE_",
							name : "role.name",
							allowBlank : false
						}, {
							fieldLabel : "描述",
							name : "role.discription",
							allowBlank : false
						}]
			});

	roleUpdateForm = new Ext.form.FormPanel({
				url : "roleAction!update.action",
				method : 'post',
				defaultType : "textfield",
				labelWidth : 55,
				defaults : {
					anchor : "92%"
				},
				baseCls : "x-plain",
				items : [{
							xtype : "hidden",
							name : "role.id"
						}, {
							fieldLabel : "名称",
							vtype : "role",
							name : "role.name",
							allowBlank : false
						}, {
							fieldLabel : "描述",
							name : "role.discription",
							allowBlank : false
						}]

			});

	addRoleWin = new Ext.Window({
				layout : 'fit',
				buttonAlign : 'center',
				width : 330,
				height : 180,
				closeAction : 'hide',
				modal : true,
				plain : true,
				buttons : [{
							text : '保存',
							handler : function() {
								// alert(roleAddForm.getForm().url);
								roleAddForm.getForm().submit({

											success : function(form, action) {
												roleAddForm.getForm().reset();
												addRoleWin.hide();
												roleGrid.getStore().removeAll();
												roleGrid.getStore().load({
															params : {
																start : 0,
																limit : pageSize
															}
														});
											},
											failure : function(form, action) {
												Ext.Msg.alert('提示', '原因如下：'
																+ "df");
											},

											waitMsg : '保存数据...'
										});
							}
						}, {
							text : '清空',
							handler : function() {
								roleAddForm.getForm().reset();
							}
						}, {
							text : '关闭',
							handler : function() {
								roleAddForm.getForm().reset();
								addRoleWin.hide();
							}
						}],
				items : [roleAddForm]
			});

	updateRoleWin = new Ext.Window({
				layout : 'fit',
				buttonAlign : 'center',
				width : 330,
				height : 180,
				closeAction : 'hide',
				modal : true,
				plain : true,
				buttons : [{
							text : '保存',
							handler : function() {
								roleUpdateForm.getForm().submit({
											success : function(form, action) {
												roleUpdateForm.getForm()
														.reset();
												updateRoleWin.hide();
												roleGrid.getStore().removeAll();
												roleGrid.getStore().load({
															params : {
																start : 0,
																limit : pageSize
															}
														});
											},
											waitMsg : '保存数据...'
										});
							}
						}, {
							text : '取消',
							handler : function() {
								roleUpdateForm.getForm().reset();
								updateRoleWin.hide();
							}
						}],
				items : [roleUpdateForm]
			});

	searchRoleWin = new Ext.Window({
				title : '查找角色',
				layout : 'form',
				width : 300,
				height : 180,
				closeAction : 'hide',
				buttonAlign : 'center',
				labelWidth : 55,
				modal : true,
				plain : true,

				buttons : [{
					text : '查找',
					handler : function() {
						roleGrid.getStore().removeAll();
						roleGrid.reconfigure(ro_s_store, ro_cm);
						// alert("name:" + Ext.getCmp("searchName").getValue());
						ro_s_store.load({
									params : {
										start : 0,
										limit : pageSize,
										"role.id" : Ext.getCmp("searchId")
												.getValue(),
										"role.name" : Ext.getCmp("searchName")
												.getValue()
									}
								});
						searchRoleWin.hide();
						Ext.getCmp("searchId").setValue("");
						Ext.getCmp("searchName").setValue("ROLE_");
					}

				}, {
					text : '取消',
					handler : function() {
						searchRoleWin.hide();
						Ext.getCmp("searchId").setValue("");
						Ext.getCmp("searchName").setValue("ROLE_");
					}
				}],
				items : [{
							fieldLabel : '编号',
							width : 200,
							id : 'searchId',
							name : 'searchId',
							// allowBlank : false,
							xtype : 'textfield'

						}, {

							fieldLabel : '角色名',
							id : 'searchName',
							value : "ROLE_",
							name : 'searchName',
							width : 200,
							// allowBlank : false,
							xtype : 'textfield'

						}]

			});

	ro_cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
			new Ext.grid.CheckboxSelectionModel(), {

				header : "编号",

				align : "center",

				dataIndex : "id"

			}, {

				header : "名称",

				align : "center",

				dataIndex : "name"

			}, {

				header : "描述",

				dataIndex : "discription",

				align : "center"

			}]);

	re_cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
			new Ext.grid.CheckboxSelectionModel(), {

				header : "编号",

				align : "center",

				dataIndex : "id"

			}, {

				header : "资源类型",

				align : "center",

				dataIndex : "type"

			}, {

				header : "权限值",

				width : 500,

				dataIndex : "value",

				align : "center"

			}]);

	ro_l_store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : "roleAction!list.action"
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'role_list',
							successProperty : 'SUCCESS',
							fields : [{
										name : 'id',
										mapping : 'id'
									}, {
										name : 'name',
										mapping : 'name'
									}, {
										name : 'discription',
										mapping : 'discription'
									}]
						}),

				sortInfo : {
					field : 'id',
					direction : 'ASC'
				}

			});

	ro_s_store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : "roleAction!search.action"
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'role_list',
							successProperty : 'SUCCESS',
							fields : [{
										name : 'id',
										mapping : 'id'
									}, {
										name : 'name',
										mapping : 'name'
									}, {
										name : 'discription',
										mapping : 'discription'
									}]
						}),

				sortInfo : {
					field : 'id',
					direction : 'ASC'
				}

			});

	re_l_store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : "resourceAction!list.action"
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'resource_list',
							successProperty : 'SUCCESS',
							fields : [{
										name : 'id',
										mapping : 'id'
									}, {
										name : 'type',
										mapping : 'type'
									}, {
										name : 'value',
										mapping : 'value'
									}]
						}),

				sortInfo : {
					field : 'id',
					direction : 'ASC'
				}

			});

	re_s_store = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : "roleAction!searchResources.action"
						}),
				reader : new Ext.data.JsonReader({
							totalProperty : 'totalProperty',
							root : 'resource_list',
							successProperty : 'SUCCESS',
							fields : [{
										name : 'id',
										mapping : 'id'
									}, {
										name : 'type',
										mapping : 'type'
									}, {
										name : 'value',
										mapping : 'value'
									}]
						}),

				sortInfo : {
					field : 'id',
					direction : 'ASC'
				}

			});

	roleGrid = new Ext.grid.GridPanel({
		renderTo : 'gridPanel',
		store : ro_l_store,
		cm : ro_cm,
		autoHeight : true,
		title : '角色信息',
		frame : true,
		stripeRows : true,
		tbar : [{
					text : "添加角色",
					handler : function() {
						addRoleWin.show();
					},
					scope : this
				}, "-", {
					text : "修改角色",
					handler : function() {
						var sm = roleGrid.getSelectionModel();
						if (sm.hasSelection()) {
							updateRoleWin.show();
							try {
								var data = roleGrid.getSelectionModel()
										.getSelected();
								var myNewRecord = new TopicRecord({
											'role.id' : data.get("id"),
											'role.name' : data.get("name"),
											'role.discription' : data
													.get("discription")
										});
								roleUpdateForm.getForm()
										.loadRecord(myNewRecord);

							} catch (_err) {
								Ext.Msg.alert("系统提示", _err.description);
								updateRoleWin.hide();
							}
						} else {
							Ext.Msg.alert('信息', "请选中一行！");
						}
					},
					scope : this
				}, "-", {
					text : "删除角色",
					handler : function() {
						var sm = roleGrid.getSelectionModel();
						if (sm.hasSelection()) {
							Ext.Msg.confirm('信息', '确定要删除?', function(btn) {
								if (btn == 'yes') {
									var _sr = roleGrid.getSelectionModel()
											.getSelections();
											ro_sel_ids = [];
									for (var i = 0; i < _sr.length; i++) {
										ro_sel_ids[i] = _sr[i].get("id");
									}
									try {
										Ext.Ajax.request({
													url : "roleAction!delete.action",
													success : function() {
														Ext.Msg.alert('信息',
																"删除成功！");
													},
													failure : function() {
														Ext.Msg
																.alert('信息',
																		"删除失败，有人员占有该角色！");
													},

													params : {
														selectedList : ro_sel_ids
													}
												});
									} catch (_err) {
										Ext.Msg.alert('信息', "用人员占有该角色，不能删除！");
									}
									for (var i = 0; i < _sr.length; i++) {
										// alert(_sr[i].get("id"));
										roleGrid.getStore().remove(roleGrid
												.getStore().getAt(_sr[i]
														.get("id")));
									}
									roleGrid.getStore().removeAll();
									roleGrid.getStore().reload({
												params : {
													start : 0,
													limit : pageSize
												}
											});
								} else {
									Ext.Msg.alert('信息', "请选中一行！");
								}
							});
						} else {
							Ext.Msg.alert('信息', "请选中纪录！");
						}
					},
					scope : this
				}, "-", {
					text : "查找角色",
					handler : function() {
						searchRoleWin.show();
					},
					scope : this
				}, "-", {
					text : "分配权限",
					handler : function() {
						var sm = roleGrid.getSelectionModel();
						if (sm.hasSelection()) {
							var record = sm.getSelected();
							current_selected_id = record.get("id");

							current_selected_name = record.get("name");
							alert(':' + current_selected_name);
							roleGrid.hide();
							resourceGrid.setTitle("角色" + current_selected_name
									+ "的资源列表");
							resourceGrid.show();
							re_s_store.load({
										params : {
											start : 0,
											limit : pageSize,
											current_selected_id : current_selected_id
										}
									});
						} else {
							Ext.Msg.alert('信息', "请选中一行！");
						}
					},
					scope : this
				}],
		enableColumnMove : false,
		selModel : new Ext.grid.CheckboxSelectionModel(),
		bbar : new Ext.PagingToolbar({
					pageSize : pageSize,
					store : ro_l_store
				})
	});

	resourceGrid = new Ext.grid.GridPanel({
		renderTo : 'gridPanel',
		title : "资源列表",
		store : re_s_store,
		cm : re_cm,
		autoHeight : true,
		frame : true,
		stripeRows : true,
		tbar : [{
			text : "添加资源",
			handler : function() {
				addResourcesWin.show();
				addResourcesGrid.setTitle("为角色" + current_selected_name
						+ "添加资源权限");
				addResourcesGrid.show();
				addResourcesGrid.getStore().load({
							params : {
								start : 0,
								limit : pageSize
							}
						});
				addResourcesWin.center();
			},
			scope : this
		}, "-", {
			text : "删除资源",
			handler : function() {
				var sm = resourceGrid.getSelectionModel();
				if (sm.hasSelection()) {
					Ext.Msg.confirm('信息', '确定要删除?', function(btn) {
						if (btn == 'yes') {
							var _sr = resourceGrid.getSelectionModel()
									.getSelections();
							re_sel_ids = [];
							for (var i = 0; i < _sr.length; i++) {
								re_sel_ids[i] = _sr[i].get("id");
							}
							Ext.Ajax.request({
										url : "roleAction!deleteResources.action",
										params : {
											selectedResourceList : re_sel_ids,
											current_selected_id : current_selected_id
										}
									});

							/*
							 * for (var i = 0; i < _sr.length; i++) { //
							 * alert(_sr[i].get("id")); resourceGrid .getStore()
							 * .remove(resourceGrid .getStore()
							 * .getAt(_sr[i].get("id"))); }
							 */

							resourceGrid.getStore().removeAll();
							resourceGrid.getStore().reload({
										params : {
											start : 0,
											limit : pageSize,
											current_selected_id : current_selected_id
										}
									});
							resourceGrid.getStore().removeAll();
							resourceGrid.getStore().reload({
										params : {
											start : 0,
											limit : pageSize,
											current_selected_id : current_selected_id
										}
									});
						} else {
							Ext.Msg.alert('信息', "请选中一行！");
						}
					});
				} else {
					Ext.Msg.alert('信息', "请选中纪录！");
				}
			},
			scope : this
		}, "-", {
			text : "角色列表",
			handler : function() {
				resourceGrid.hide();
				roleGrid.show();
			},
			scope : this
		}],
		enableColumnMove : false,
		selModel : new Ext.grid.CheckboxSelectionModel(),
		bbar : new Ext.PagingToolbar({
					pageSize : pageSize,
					store : re_s_store
				})
	});

	addResourcesGrid = new Ext.grid.GridPanel({
		store : re_l_store,
		cm : re_cm,
		title : "添加资源权限",
		autoHeight : true,
		autoWidth : true,
		frame : true,
		stripeRows : true,
		tbar : [{
			text : "添加资源",
			handler : function() {
				var sm = addResourcesGrid.getSelectionModel();
				if (sm.hasSelection()) {
					Ext.Msg.confirm('信息', '确定要添加?', function(btn) {
						if (btn == 'yes') {
							var _sr = addResourcesGrid.getSelectionModel()
									.getSelections();
							re_sel_ids = [];
							for (var i = 0; i < _sr.length; i++) {
								re_sel_ids[i] = _sr[i].get("id");
							}
							alert("current_selected_id:" + current_selected_id);
							Ext.Ajax.request({
										url : "roleAction!addResources.action",
										params : {
											selectedResourceList : re_sel_ids,
											current_selected_id : current_selected_id
										}
									});

							addResourcesWin.hide();
							resourceGrid.getStore().removeAll();
							resourceGrid.getStore().reload({
										params : {
											start : 0,
											limit : pageSize,
											current_selected_id : current_selected_id
										}
									});
						} else {
							Ext.Msg.alert('信息', "请选中一行！");
						}
					});
				} else {
					Ext.Msg.alert('信息', "请选中纪录！");
				}
			},
			scope : this
		}],
		enableColumnMove : false,
		selModel : new Ext.grid.CheckboxSelectionModel(),
		bbar : new Ext.PagingToolbar({
					pageSize : pageSize,
					store : re_l_store
				})
	});

	addResourcesWin = new Ext.Window({
				layout : 'fit',
				width : 330,
				height : 180,
				closeAction : 'hide',
				modal : true,
				plain : true,
				autoHeight : true,
				autoWidth : true,
				items : [addResourcesGrid]
			});

	re_s_store.on('beforeload', function() {
								Ext.apply(this.baseParams, {
									current_selected_id : current_selected_id
								});
							});		
			
	roleGrid.getStore().load({
				params : {
					start : 0,
					limit : pageSize
				}
			});
	resourceGrid.hide();
	addResourcesGrid.hide();
});
